package stardust.core.network.protocol.http;


import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import stardust.core.network.NetworkSessionInputStream;


public class HttpRequestMeta
{

  private HttpMethod method;

  private String requestURI;

  private HttpVersion version;

  private byte[] data;

  private Map<String, String> others = new HashMap<String, String>();

  public String getRequest()
  {
    StringBuffer buff = new StringBuffer();

    buff.append(this.method).append(" ").append(this.requestURI).append(" ").append(this.version).append("\r\n");

    Iterator<String> keys = this.others.keySet().iterator();
    String key, value;

    while (keys.hasNext())
    {
      key = keys.next();
      value = this.others.get(key);

      buff.append(key).append(": ").append(value).append("\r\n");
    }

    return buff.append("\r\n").toString();
  }

  public HttpMethod getMethod()
  {
    return method;
  }

  public void setMethod(HttpMethod method)
  {
    this.method = method;
  }

  public String getRequestURI()
  {
    return requestURI;
  }

  public void setRequestURI(String requestURI)
  {
    this.requestURI = requestURI;
  }

  public HttpVersion getVersion()
  {
    return version;
  }

  public void setVersion(HttpVersion version)
  {
    this.version = version;
  }

  public Map<String, String> getOthers()
  {
    return others;
  }

  public byte[] getData()
  {
    return data;
  }

  public void setData(byte[] data)
  {
    this.data = data;
  }

  public static HttpRequestMeta parse(NetworkSessionInputStream reader) throws IOException
  {
    HttpRequestMeta meta = new HttpRequestMeta();
    String cmd, key, value;
    String[] tmpCmd;

    cmd = reader.readLine();

    if (cmd == null)
    {
      return null;
    }
    
    tmpCmd = cmd.split("[ ]", 3);
    meta.method = HttpMethod.get(tmpCmd[0]);
    meta.requestURI = tmpCmd[1];
    meta.version = HttpVersion.get(tmpCmd[2]);

    while ((cmd = reader.readLine()) != null && cmd.length() > 0)
    {
      tmpCmd = cmd.split(":", 2);

      if (tmpCmd.length == 2)
      {
        key = tmpCmd[0].trim();
        value = tmpCmd[1].trim();
      }
      else
      {
        key = "UNKNOW";
        value = cmd;
      }

      meta.others.put(key, value);
    }
    return meta;
  }

}
